use std::sync::Arc;

use openssl::{
    error::ErrorStack,
    ssl::{SslContext, SslMethod, SslOptions},
};

use crate::config::ssl::connector::SslConnectorRuntimeConf;

use super::base::{ctx_builder, SslInitialization};

pub struct CustomConnectorBuilder {
    conf: Arc<SslConnectorRuntimeConf>,
}

#[allow(dead_code)]
impl CustomConnectorBuilder {
    pub fn new(conf: Arc<SslConnectorRuntimeConf>) -> Self {
        CustomConnectorBuilder { conf }
    }

    pub fn build(self) -> Result<SslContext, ErrorStack> {
        let ssl_initlization = SslInitialization::get_instance();

        let mut ctx_builder = ctx_builder(SslMethod::tls_client())?;
        ctx_builder.set_options(SslOptions::NO_SSLV3);
        ctx_builder.set_default_verify_paths()?;

        if !self.conf.cipher_list.is_empty() {
            ctx_builder.set_cipher_list(&self.conf.cipher_list)?;
        }

        // TODO:
        // 参考: SslConnector::builder
        // setup_verify(ctx_builder)

        let arc_self = Arc::new(self);
        ctx_builder.set_ex_data(
            ssl_initlization.connector_builder_index,
            arc_self.clone(),
        );
        Ok(ctx_builder.build())
    }
}
